package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.controller.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author fan
 * @since 2021-11-22
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private DictMapper dictMapper;
    @SneakyThrows
    @Override
    public boolean importData(MultipartFile multipartFile) {

            EasyExcel.read(multipartFile.getInputStream(), ExcelDictDTO.class,new ExcelDictDTOListener(dictMapper)).sheet("数据字典").doRead();
            return true;

    }

    @Override
    public List<Dict> listDick(Long parentId) {
        //从缓存中查数据
        List<Dict> dicts;
        try {
            dicts = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dicts:" + parentId);
            if (dicts != null) {
                log.info("从redis中取值");
                return dicts;
            }
        }catch (Exception e){
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }

        log.info("数据库中取值");
        //new一个Dict类型的条件构造器对象
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        //构造查询条件：字段parent_id与方法参数parentId相等返回true
        dictQueryWrapper.eq("parent_id",parentId);
        //调用mapper方法根据查询条件dictQueryWrapper查询列表
        dicts = dictMapper.selectList(dictQueryWrapper);
        for (Dict dict : dicts) {
            Long dictId = dict.getId();
            Boolean b = hasChildren(dictId);
            dict.setHasChildren(b);
        }
        try{
            log.info("存值到redis");
            redisTemplate.opsForValue().set("srb:core:dicts:"+parentId,dicts,5, TimeUnit.MINUTES);
        }catch (Exception e){
            log.error("redis服务器异常：" + ExceptionUtils.getStackTrace(e));
        }
        return dicts;
    }

    @Override
    public List<Dict> getDictListByDictCode(String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        Long parentId = dict.getId();

        QueryWrapper<Dict> dictQueryWrapper1 = new QueryWrapper<>();
        dictQueryWrapper1.eq("parent_id",parentId);
        List<Dict> dictList = baseMapper.selectList(dictQueryWrapper1);


        return dictList;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<Dict>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);

        if(parentDict == null) {
            return "";
        }

        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .eq("parent_id", parentDict.getId())
                .eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);

        if(dict == null) {
            return "";
        }

        return dict.getName();
    }

    private Boolean hasChildren(Long dictId) {
        boolean b = false;
        //new一个Dict类型的条件构造器对象
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        //构造查询条件：字段parent_id与方法参数dictId相等返回true
        dictQueryWrapper
                .eq("parent_id",dictId);
        //调用mapper方法根据查询条件dictQueryWrapper查询数量
        Integer integer = dictMapper.selectCount(dictQueryWrapper);
        //integer<=0则代表该parent_id下没有子分类、页面中不需要设置下拉按钮
        if (integer>0){
            return true;
        }return false;
    }
}
